// @ts-ignore
import ParkInfoWindow from "../components/InfoWindow/ParkInfoWindow.vue";
import {GlobalVariables} from "../GlobalVariables";
import {createApp} from "vue";
import {EventBus} from "./EventBus";
import {ElMessage} from 'element-plus';

//构造地点查询类
const placeSearch = new AMap.PlaceSearch({
    type: "150900|150903|150904|150905|150906|150907|150908|150909", // 兴趣点类别
    pageSize: 50, // 单页显示结果条数
    pageIndex: 1, // 页码
    city: "福州市", // 兴趣点城市
    citylimit: true,  //是否强制限制在设置的城市内搜索
    // map: GlobalVariables.map, // 展现结果的地图实例
    renderStyle: "default",
    autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
});
let driving: AMap.Driving;
let trafficLayer: AMap.TileLayer.Traffic;
EventBus.bus.on(EventBus.mapLoaded, () => {
    // 构造路线导航类
    driving = new AMap.Driving({
        ferry: 1, // 是否可以使用轮渡
        map: GlobalVariables.map
    });
})

let dragMarker:any = null;//可拖拽的标记点
let cluster: any = null;//停车场的点聚合对象
let placeSearchOverlayGroups: any = null;//
export class AMapUtil {
    //地图加载完成
    public static onMapLoaded(func: any) {
        if (GlobalVariables.map) {
            setTimeout(func,300);//防止前一个页面销毁在后，新页面创建在前
        } else {
            EventBus.bus.on(EventBus.mapLoaded, func);
        }
    }
    //添加拖拽图标
    public static addDragMarker(callBack:any){
        if(dragMarker){
            return;
        }
        dragMarker = new AMap.Marker({
            position: GlobalVariables.map.getCenter(),
            icon: new AMap.Icon({
                image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
                size: new AMap.Size(22, 28),  //图标所处区域大小
                imageSize: new AMap.Size(22,28) //图标大小
            }),
            offset: new AMap.Pixel(-11, -28),
            draggable: true, // 设置是否可以拖拽
            cursor: 'move',
            raiseOnDrag: true, // 设置拖拽效果
        });
        console.log(dragMarker)
        dragMarker.on("dragend",callBack);
        GlobalVariables.map.add(dragMarker)
        // dragMarker.setMap(GlobalVariables.map);
    }
    //移除拖拽图标
    public static removeDragMarker(){
        if(dragMarker){
            GlobalVariables.map.remove(dragMarker);
            dragMarker.remove
            dragMarker = null;
        }
    }
    //实时路况图层
    public static showTraffic() {
        if (trafficLayer) {
            trafficLayer.show();
        } else {
            trafficLayer = new AMap.TileLayer.Traffic({
                zIndex: 10,
                zooms: [7, 22]
            });
            trafficLayer.setMap(GlobalVariables.map);
        }
    }

    //隐藏路况
    public static hideTraffic() {
        if (trafficLayer) {
            trafficLayer.hide();
        }
    }

    //创建弹窗
    public static createInfoWindow(vDon: any, position: any, props: any) {
        const content = document.createElement("div");
        createApp(vDon, props).mount(content);
        var infoWindow = new AMap.InfoWindow({
            isCustom: true,  //使用自定义窗体
            content: content,
            offset: new AMap.Pixel(16, -45)
        });
        infoWindow.open(GlobalVariables.map, position);
    }

    //周边搜索停车场
    public static PlaceSearch(center: any, radius: number) {
        AMapUtil.clearPlaceSearch();
        placeSearch.searchNearBy('', center, radius, function (status: any, result: any) {
            if (status !== "complete") {
                ElMessage.error("搜索错误");
            }
            var circle: any = new AMap.Circle({
                center: center,
                radius: radius, //半径
                borderWeight: 3,
                strokeColor: "#FF33FF",
                strokeOpacity: 1,
                strokeWeight: 6,
                fillOpacity: 0.3,
                strokeStyle: 'dashed',
                strokeDasharray: [10, 10],
                fillColor: '#1791fc',
                zIndex: 50,
            })
            const markers = result.poiList.pois.map((park: any) => {
                const marker: any = new AMap.Marker({
                    title: park.title,
                    extData: park,
                    position: park.location,
                    icon:"./images/空闲停车icon.png",
                    // content: `<div class="parkicon">车</div>`,
                    offset: new AMap.Pixel(-15, -15)
                });
                marker.on("click", (ree: any) => {
                    park.isNavigation = true;
                    park.callBack = (park_: any) => {
                        AMapUtil.Driving(GlobalVariables.curPosition, [park_.location.lng, park_.location.lat]);
                    }
                    AMapUtil.createInfoWindow(ParkInfoWindow, marker.getPosition(), park)
                })
                return marker;
            });
            markers.push(circle)
            placeSearchOverlayGroups = new AMap.OverlayGroup(markers);
            GlobalVariables.map.add(placeSearchOverlayGroups);
            GlobalVariables.map.setFitView(markers)
        });
    }

    //清空周边搜索停车场
    public static clearPlaceSearch() {
        if (placeSearchOverlayGroups) {
            GlobalVariables.map.remove(placeSearchOverlayGroups);
            placeSearchOverlayGroups = null;
        }
    }

    //路线规划
    public static Driving(sp: any, ep: any, policy = AMap.DrivingPolicy.LEAST_FEE, callBack?: Function) {
        AMapUtil.clearDriving();
        driving.setPolicy(policy);
        // 根据起终点经纬度规划驾车导航路线
        driving.search(sp, ep, function (status: any, result: any) {
            // result即是对应的驾车导航信息，相关数据结构文档请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
            if (status === 'complete') {
                if (result.routes && result.routes.length) {
                    if (callBack) {
                        const result2: any = {
                            "未知": [],
                            "畅通": [],
                            "缓行": [],
                            "拥堵": [],
                            "严重拥堵": [],
                        }
                        for (let step of result.routes[0].steps) {
                            if (step.tmcs.length === 0) {
                                continue;
                            }
                            for(let tmc of step.tmcs){
                                if (result2[tmc.status]) {
                                    tmc.road = step.road;
                                    result2[tmc.status].push(tmc);
                                }
                            }

                        }
                        callBack(result.routes[0], result2);
                    }
                    ElMessage.success('绘制路线完成')
                }
            } else {
                ElMessage.error('获取数据失败：' + result)
            }
        });
    }

    //清空路线规划
    public static clearDriving() {
        if(driving != null){
            driving.clear();
        }
    }

    //创建停车场的聚合点
    public static async createParkingSpotCluster() {
        AMapUtil.clearParkingSpotCluster();
        const res = await GlobalVariables.axios.get("./json/park.json");
        const markers = res.data.map((park: any) => {
            const position = park.location.split(",");
            const marker: any = new AMap.Marker({
                title: park.name,
                extData: park,
                position: position,
                icon:"./images/占用停车icon.png",
                // content: `<div class="parkicon">车</div>`,
                offset: new AMap.Pixel(-15, -15)
            });
            marker.on("click", (ree: any) => {
                AMapUtil.createInfoWindow(ParkInfoWindow, marker.getPosition(), park)
            })
            return marker;
        })
        cluster = new AMap.MarkerClusterer(GlobalVariables.map, markers, {gridSize: 80});
    }

    //清除停车场的聚合点
    public static clearParkingSpotCluster() {
        if (cluster) {
            GlobalVariables.map.remove(cluster);
            cluster = null;
        }
    }
}
